<template>
  <div class='ele-body ele-body-card'>
    <a-divider>喷淋默认配置设置</a-divider>
    <a-alert
      message="警告"
      type="warning"
      show-icon
      style="margin-bottom: 16px"
      :description-style="{ whiteSpace: 'pre-line' }"
    >
      <template #description>
        <div class="alert-description">
          <p>①不受时间控制+间歇喷淋+无算法: 不受时间段控制;没有算法,根据`喷淋时长`和`间隔时长`配置进行轮询喷淋,喷x秒,停x秒,不断的轮询</p>          
          <p>②指定时间段喷淋+无间歇+无算法: 在指定的时间段内喷淋,不在时间段内不喷淋;没有算法,不会根据`喷淋时长`和`间隔时长`配置进行喷x秒停x秒</p>          
          <p>③不受时间控制+间歇喷淋+有算法: 不受时间段控制;有算法,相机在识别到牛的情况下,根据在`喷淋时长`和`间隔时长`配置,喷x秒停x秒进行不断的轮询;识别不到牛,就不会喷</p>
          <p>④指定时间段喷淋+无间歇+有算法: 有算法,在指定的喷淋时间段内,识别到牛就喷,没牛就不喷。不在喷淋时间段,有无牛都停。不会根据`喷淋时长`和`间隔时长`配置进行喷x秒停x秒</p>     
          <p>⑤不受时间控制+无间歇+有算法: 不受时间段控制;有算法,识别到牛就喷,识别不到牛就不喷,不会根据`喷淋时长`和`间隔时长`配置进行喷x秒停x秒</p>
          <p class="warning">同步到相机的操作会覆盖相机当前的喷淋配置，会直接把喷淋时间段覆盖，请谨慎操作！</p>
          <p>保存到数据库会作为调度过程中的一些默认项</p>
        </div>
      </template>
    </a-alert>

    <a-card
      :bordered='true'
      :body-style="{padding: '20px'}">
      <a-form
        ref='sprayFormRef'
        :model='sprayFormModel'
        :rules="sprayFormRules"
        :label-col='{ md: { span: 7 }, sm: { span: 24 } }'
        :wrapper-col='{ md: { span: 17 }, sm: { span: 24 } }'
      >
        <a-row :gutter='8'>
          <a-col :md='10' :sm='24' :xs='24'>
            <a-form-item label='喷淋时长(秒):' name='spray'>
              <a-input-number v-model:value='sprayFormModel.spray' placeholder='请输入喷淋时长' :min="0" />
            </a-form-item>
          </a-col>
          <a-col :md='12' :sm='24' :xs='24'/>
        </a-row>

        <a-row :gutter='8'>
          <a-col :md='10' :sm='24' :xs='24'>
            <a-form-item label='识别容忍度(秒):' name='identify'>
              <a-input-number v-model:value='sprayFormModel.identify' placeholder='请输入识别容忍度' :min="0" />
            </a-form-item>
          </a-col>
          <a-col :md='12' :sm='24' :xs='24'/>
        </a-row>

        <a-row :gutter='8'>
          <a-col :md='10' :sm='24' :xs='24'>
            <a-form-item label='间隔时长(秒):' name='sprayInterval'>
              <a-input-number v-model:value='sprayFormModel.sprayInterval' placeholder='请输入间隔时长' :min="0" />
            </a-form-item>
          </a-col>
          <a-col :md='12' :sm='24' :xs='24'/>
        </a-row>

        <a-row :gutter='8'>
          <a-col :md='10' :sm='24' :xs='24'>
            <a-form-item label='喷淋模式:' name='ignoreAlg'>
              <a-select v-model:value="sprayFormModel.ignoreAlg">
                <a-select-option :value="0">请选择</a-select-option>
                <a-select-option :value="1">不受时间控制+间歇喷淋+无算法[旧版本：传统喷淋]</a-select-option>
                <a-select-option :value="2">指定时间段喷淋+无间歇+无算法[旧版本：视觉喷淋]</a-select-option>
                <a-select-option :value="3">不受时间控制+间歇喷淋+有算法[旧版本：传统喷淋+视觉喷淋]</a-select-option>
                <a-select-option :value="4">指定时间段喷淋+无间歇+有算法</a-select-option>
                <a-select-option :value="5">不受时间控制+无间歇+有算法</a-select-option>
                <a-select-option :value="127">不喷淋</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md='12' :sm='24' :xs='24'/>
        </a-row>

        <!-- 新增时间段配置 -->
        <a-row :gutter='8'>
          <a-col :md='10' :sm='24' :xs='24'>
            <a-form-item label='喷淋时间段:' name='timeSlot'>
              <div>
                <div v-for="(timeRange, index) in sprayFormModel.timeSlot" :key="index" style="display: flex; margin-bottom: 8px; align-items: center;">
                  <a-time-picker 
                    v-model:value="timeRange[0]" 
                    format="HH:mm:ss" 
                    placeholder="开始时间"
                    style="width: 150px; margin-right: 8px;"
                    @change="(time) => updateTimeSlot(index, 0, time)"
                  />
                  <a-form-item-rest>
                    <span style="margin: 0 8px;">至</span>
                    <a-time-picker 
                      v-model:value="timeRange[1]" 
                      format="HH:mm:ss" 
                      placeholder="结束时间"
                      style="width: 150px; margin-right: 8px;"
                      @change="(time) => updateTimeSlot(index, 1, time)"
                    />
                    <a-button 
                      type="danger" 
                      shape="circle"
                      @click="removeTimeSlot(index)"
                    >
                      <template #icon><delete-outlined /></template>
                    </a-button>
                  </a-form-item-rest>
                </div>
                <a-button type="dashed" style="width: 100%; margin-top: 8px;" @click="addTimeSlot">
                  <plus-outlined /> 添加时间段
                </a-button>
              </div>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter='8'>
          <a-col :md='4' :sm='24' :xs='24'>
            <a-button type='primary' @click="setSprayActionToCmdQueue()" :loading='sprayFormRefLoading' v-permission="['PROPERTY_DEVICELIST_MGR_SPRAYCAMERA_CONFIG_SPRAYRULE_SET2CLIENT_BUTTONG']">
              保存到数据并同步到相机
            </a-button>
          </a-col>
          <a-col :md='4' :sm='24' :xs='24'>
            <a-button type='primary' @click="saveSprayActionToDb()" v-permission="['PROPERTY_DEVICELIST_MGR_SPRAYCAMERA_CONFIG_SPRAYRULE_SET2DB_BUTTONG']">
              保存到数据库
            </a-button>
          </a-col>
          <a-col :md='5' :sm='24' :xs='24'>
            <a-button type='primary' @click="syncToSomeOxtall()" v-permission="['PROPERTY_DEVICELIST_MGR_SPRAYCAMERA_CONFIG_SPRAYRULE_SET2CLIENTOXTALL_BUTTONG']">
              保存到数据库并同步到相同牛舍下的所有设备
            </a-button>
          </a-col>
          <a-col :md='9' :sm='24' :xs='24' />
        </a-row>
      </a-form>
    </a-card>

    <!--
    <a-divider>喷淋模式设置</a-divider>
    <a-card
      :bordered='true'
      :body-style="{padding: '20px'}">
      <a-form
        ref='sprayModeRef'
        :model='sprayModeModel'
        :rules="sprayModeRules"
        :label-col='{ md: { span: 7 }, sm: { span: 24 } }'
        :wrapper-col='{ md: { span: 17 }, sm: { span: 24 } }'
      >
        <a-row :gutter='8'>
          <a-col :md='12' :sm='24' :xs='24'>
            <a-form-item label='喷淋模式:' name='spraymode'>
              <a-select v-model:value="spraymode">
                <a-select-option :value="0">请选择</a-select-option>
                <a-select-option :value="1">不受时间控制+间歇喷淋+无算法[旧版本：传统喷淋]</a-select-option>
                <a-select-option :value="2">指定时间段喷淋+无间歇+无算法[旧版本：视觉喷淋]</a-select-option>
                <a-select-option :value="3">不受时间控制+间歇喷淋+有算法[旧版本：传统喷淋+视觉喷淋]</a-select-option>
                <a-select-option :value="4">指定时间段喷淋+无间歇+有算法</a-select-option>
                <a-select-option :value="5">不受时间控制+无间歇+有算法</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md='10' :sm='24' :xs='24'/>
        </a-row>
        <a-row :gutter='8'>
          <a-col :md='5' :sm='24' :xs='24'>
            <a-button type='primary' @click="setSprayModeToCmdQueue()" :loading='sprayModeRefLoading'>
              同步到相机
            </a-button>
          </a-col>
          <a-col :md='5' :sm='24' :xs='24'>
            <a-col :md='5' :sm='24' :xs='24'>
            <a-button type='primary' @click="syncModeToSomeOxtall()" >
              同步到相同牛舍下的所有设备
            </a-button>
          </a-col>
          </a-col>
          <a-col :md='12' :sm='24' :xs='24' />
        </a-row>
      </a-form>
    </a-card>
-->
  </div>
</template>

<script>
import {DeviceCommandDownQueueApi} from '@/api/property/DeviceCommandDownQueueApi';
import { message } from 'ant-design-vue';
import {DeviceSprayCameraStaticConfigApi} from "@/api/property/spraycamera/DeviceSprayCameraStaticConfigApi";
import {DeviceCommandTemplateDistributeApi} from "@/api/property/DeviceCommandTemplateDistributeApi";
import { PlusOutlined, DeleteOutlined } from '@ant-design/icons-vue';
import dayjs from 'dayjs';

export default {
  name: 'DeviceSpraycameraSprayruleConfig',
  components: {
    PlusOutlined,
    DeleteOutlined
  },
  props: {
    data: Object
  },
  async created() {
    await this.init();
  },
  data() {
    return {
      loading : false,
      sourceConfig : {},
      sprayFormModel: {
        timeSlot: []
      },
      sprayFormRules: {},
      sprayFormRefLoading: false,
      sprayFormRefTimer: undefined,


      sprayModeModel : {},
      sprayModeRules : {},
      sprayModeRefLoading : false,
      sprayModeRefTimer : undefined,
      spraymode : 0

    };
  },
  methods: {
    async init() {
      let _conf = await DeviceSprayCameraStaticConfigApi.detail({'recordId': this.data.recordId});
      if (_conf) {
        this.sourceConfig = _conf;

        this.sprayFormModel.spray = _conf.spray;
        this.sprayFormModel.identify = _conf.identify;
        this.sprayFormModel.sprayInterval = _conf.sprayInterval;
        this.sprayFormModel.ignoreAlg = _conf.ignoreAlg;
        this.sprayFormModel.recordId = _conf.recordId;
        
        // 初始化时间段数据 - 将JSON字符串转为数组
        if (_conf.timeSlot) {
          try {
            // 尝试解析JSON字符串
            const timeSlotArray = JSON.parse(_conf.timeSlot);
            if (Array.isArray(timeSlotArray)) {
              this.sprayFormModel.timeSlot = timeSlotArray.map(slot => {
                return [
                  slot[0] ? dayjs(slot[0], 'HH:mm:ss') : null,
                  slot[1] ? dayjs(slot[1], 'HH:mm:ss') : null
                ];
              });
            } else {
              this.sprayFormModel.timeSlot = [];
            }
          } catch (e) {
            console.error('解析timeSlot失败:', e);
            this.sprayFormModel.timeSlot = [];
          }
        } else {
          this.sprayFormModel.timeSlot = [];
        }
      }
    },
    
    // 添加时间段
    addTimeSlot() {
      this.sprayFormModel.timeSlot.push([null, null]);
    },
    
    // 删除时间段
    removeTimeSlot(index) {
      this.sprayFormModel.timeSlot.splice(index, 1);
    },
    
    // 更新时间段
    updateTimeSlot(index, position, time) {
      this.sprayFormModel.timeSlot[index][position] = time;
    },
    
    // 格式化时间段数据用于保存 - 转为JSON字符串
    formatTimeSlotForSave() {
      const formattedTimeSlot = this.sprayFormModel.timeSlot.map(slot => {
        return [
          slot[0] ? slot[0].format('HH:mm:ss') : null,
          slot[1] ? slot[1].format('HH:mm:ss') : null
        ];
      }).filter(slot => slot[0] && slot[1]); // 过滤掉不完整的时间段
      
      // 将数组转为JSON字符串
      return JSON.stringify(formattedTimeSlot);
    },
    
    checkProcess(sceneDictate, clearCallback, callback) {
      let params = {
        recordId: this.data.recordId,
        sceneDictate: sceneDictate
      };
      let result = DeviceCommandDownQueueApi.workingDetail(params);
      result
        .then(result => {
          if (!result || !result.dcdqId) { //处理完成了
            clearCallback && clearCallback(); //去掉菊花+清除循环调用
            callback && callback(); //用户自定义
          }
        })
        .catch(() => {
          clearCallback && clearCallback(); //去掉菊花+清除循环调用
        });
    },


    //保存默认配置
    saveSprayConfig() {
      let that = this;
      this.loading = true;
      let result = DeviceSprayCameraStaticConfigApi.edit(this.sprayFormModel);
      result.then(result => {
        // 移除加载框
        that.loading = false;
        // 提示添加成功
        message.success(result.message);
        that.init();
      }).catch(() => {
        message.error('保存失败')
        that.loading = false;
      });
    },


    // 喷淋配置相关方法
    clearSprayFormRef() {
      this.sprayFormRefLoading = false;
      clearInterval(this.sprayFormRefTimer);
    },

    checkSpray() {
      let that = this;
      this.checkProcess(5, this.clearSprayFormRef, function () {
        that.init();
      });
    },

    setSprayActionToCmdQueue() {
      let that = this;
      let workerDetailparams = {
        recordId: this.data.recordId,
        sceneDictate: 5
      };
      let existWorkerResult = DeviceCommandDownQueueApi.workingDetail2(workerDetailparams);
      existWorkerResult
        .then(workResult => {
          if (!workResult || !workResult.dcdqId) {
            // 格式化时间段数据为JSON字符串
            const formData = {...that.sprayFormModel};
            formData.timeSlot = that.formatTimeSlotForSave();
            
            let result1 = DeviceSprayCameraStaticConfigApi.edit(formData);
            result1.then(result => {
              that.pushSpray();
            }).catch(() => {
              message.error('保存失败')
            });
          } else {
            message.error('上一个配置还在推送中，请稍后重试');
            return;
          }
        })
        .catch((e) => {
          message.error(e);
        });
    },

    pushSpray() {
      this.loading = true;
      let updateDataRecord = {
        updateData: JSON.stringify({
          old: '',
          update: ''
        }),
        recordId: this.data.recordId,
        templateCode: 'spraycamera',
        dictate: 5,
        sceneDictate: 5
      };
      let result = DeviceCommandDownQueueApi.add(updateDataRecord);
      result
        .then(result => {
          this.loading = false;
          message.success(result.message);

          this.sprayFormRefLoading = true;
          this.sprayFormRefTimer = setInterval(this.checkSpray, 5000);
        })
        .catch(() => {
          this.loading = false;
        });
    },
    // 喷淋配置相关方法end


    //喷淋模式begin
    clearSprayModeRef() {
      this.sprayModeRefLoading = false;
      clearInterval(this.sprayModeRefTimer);
    },

    checkSprayMode() {
      let that = this;
      this.checkProcess(12, this.clearSprayModeRef, function () {
        that.spraymode = 0;
      });
    },
    setSprayModeToCmdQueue() {
      if (this.spraymode == 0) {
        message.error('请先选择喷淋模式');
        return;
      }
      let that = this;
      let workerDetailparams = {
        recordId: this.data.recordId,
        sceneDictate: 12
      };
      let existWorkerResult = DeviceCommandDownQueueApi.workingDetail2(workerDetailparams);
      existWorkerResult
        .then(workResult => {
          if (!workResult || !workResult.dcdqId) {
            that.pushModeSpray();
          } else {
            message.error('上一个配置还在推送中，请稍后重试');
            return;
          }
        })
        .catch((e) => {
          message.error(e);
        });
    },
    pushModeSpray() {
      this.loading = true;
      let updateDataRecord = {
        updateData: JSON.stringify({
          old: '',
          update: {
            mode: this.spraymode - 1
          }
        }),
        recordId: this.data.recordId,
        templateCode: 'spraycamera',
        dictate: 12,
        sceneDictate: 12
      };
      let result = DeviceCommandDownQueueApi.add(updateDataRecord);
      result
        .then(result => {
          this.loading = false;
          message.success(result.message);

          this.sprayModeRefLoading = true;
          this.sprayModeRefTimer = setInterval(this.checkSprayMode, 5000);
        })
        .catch(() => {
          this.loading = false;
        });
    },
    //喷淋模式end


    saveSprayActionToDb() {
      let that = this;
      this.loading = true;
      
      // 格式化时间段数据为JSON字符串
      const formData = {...that.sprayFormModel};
      formData.timeSlot = that.formatTimeSlotForSave();
      
      let result1 = DeviceSprayCameraStaticConfigApi.edit(formData);
      result1.then(result => {
        message.success('保存成功')
        this.loading = false;
        that.init();
      }).catch(() => {
        this.loading = false;
        message.error('保存失败')
      });
    },

    syncToSomeOxtall() {
      if (this.data.oxtId <= 0) {
        message.error('当前牛舍没有其他牛舍');
        return;
      }
      let that = this;
      this.loading = true;
      // 格式化时间段数据为JSON字符串
      const formData = {...that.sprayFormModel};
      formData.timeSlot = that.formatTimeSlotForSave();
      
      let result1 = DeviceSprayCameraStaticConfigApi.edit(formData);
      result1.then(result => {
        let toObjs = {
          "oxtall_ids" : [that.data.oxtId]
        };
        let addParams = {
          "templateCode" : "spraycamera",
          "toObjs" : JSON.stringify(toObjs),
          "sceneDictate" : 5,
          "dictate" : 5,
          "templateContent" :  JSON.stringify(formData)
        };
        let result2 = DeviceCommandTemplateDistributeApi.add(addParams);
        result2.then(res => {
          // 移除加载框
          that.loading = false;
          // 提示添加成功
          message.success(res.message);
        })
          .catch(() => {
            that.loading = false;
          });
      }).catch(() => {
        message.error('保存失败')
      });
    },
    syncModeToSomeOxtall() {
      if (this.data.oxtId <= 0) {
        message.error('当前牛舍没有其他牛舍');
        return;
      }
      if (this.spraymode == 0) {
        message.error('请先选择喷淋模式');
        return;
      }
      let that = this;
      this.loading = true;
      let formData = {
        mode : this.spraymode - 1
      };

      let toObjs = {
        "oxtall_ids" : [that.data.oxtId]
      };
      let addParams = {
        "templateCode" : "spraycamera",
        "toObjs" : JSON.stringify(toObjs),
        "sceneDictate" : 12,
        "dictate" : 12,
        "templateContent" :  JSON.stringify(formData)
      };
      let result2 = DeviceCommandTemplateDistributeApi.add(addParams);
      result2.then(res => {
        // 移除加载框
        that.loading = false;
        // 提示添加成功
        message.success(res.message);
      })
        .catch(() => {
          that.loading = false;
          message.success('同步保存失败');
        });
    }


  }
};
</script>
<style scoped>
/** 用户卡片 */
.workplace-user-card .ele-cell-content {
  overflow: hidden;
}

.workplace-user-card h4 {
  margin-bottom: 6px;
}

.alert-description p {
  margin: 8px 0;
}
.alert-description .indent {
  padding-left: 24px;
}
.alert-description .warning {
  color: #ff4d4f;
  font-weight: 500;
}
</style>
